<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
error_reporting(E_ERROR | E_PARSE );
/**
 * 生成密码
 * $string 原始字符串
 * $pwd_str 扩展字符串
 * 密码生成规则：md5(pwd+扩展字符)
 */
function get_pwd($string,$pwd_str)
{
    return md5(trim($string . $pwd_str));
}

/**
 * 获取客户端IP地址
 * @param integer $type
 * @return mixed
 */
function getclientip() 
{
    static $realip = NULL;

    if($realip !== NULL)
    {
        return $realip;
    }
    if(isset($_SERVER))
    {
        if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        { /*但如果客户端是使用代理服务器来访问，那取到的就是代理服务器的 IP 地址，而不是真正的客户端 IP 地址。要想透过代理服务器取得客户端的真实 IP 地址，就要使用 $_SERVER["HTTP_X_FORWARDED_FOR"] 来读取。*/
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
            foreach ($arr AS $ip){
                $ip = trim($ip);
                if ($ip != 'unknown'){
                    $realip = $ip;
                    break;
                }
            }
        }elseif(isset($_SERVER['HTTP_CLIENT_IP']))
        {/*HTTP_CLIENT_IP 是代理服务器发送的HTTP头。如果是"超级匿名代理"，则返回none值。同样，REMOTE_ADDR也会被替换为这个代理服务器的IP。*/
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        }else{
            if (isset($_SERVER['REMOTE_ADDR']))
            { /*正在浏览当前页面用户的 IP 地址*/
                $realip = $_SERVER['REMOTE_ADDR'];
            }else{
                $realip = '0.0.0.0';
            }
        }
    }else{
        /*getenv环境变量的值*/
        if (getenv('HTTP_X_FORWARDED_FOR'))
        {/*但如果客户端是使用代理服务器来访问，那取到的就是代理服务器的 IP 地址，而不是真正的客户端 IP 地址。要想透过代理服务器取得客户端的真实 IP 地址*/
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        }elseif (getenv('HTTP_CLIENT_IP'))
        { /*获取客户端IP*/
            $realip = getenv('HTTP_CLIENT_IP');
        }else
        {
            $realip = getenv('REMOTE_ADDR');  /*正在浏览当前页面用户的 IP 地址*/
        }
    }
    preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
    $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
    return $realip;
}

/*
 * 随机生成手机6位验证码
 * @param $len int 验证码的位数
 * @param $type int 验证码类型
 * @return string
 */
function get_code($len=6,$type=1)
{
    $gatHerteam = [
        0 => ['3','4','6','7','8','9','A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','T','U','V','W','X','Y','a','b','c','d','e','f','g','h','j','k','m','n','p','q','r','t','u','v','w','x','y'],
        1 => ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'],
        2 => ['a','b','c','d','e','f','g','h','i','j','j','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'],
        3 => ['0','1','2','3','4','5','6','7','8','9'],
        4 => ['3','4','6','7','8','9','a','b','c','d','e','f','g','h','j','k','m','n','p','q','r','t','u','v','w','x','y'],
        5 => ['3','4','6','7','8','9','A','B','C','D','E','F','G','H','J','K','M','N','P','Q','R','T','U','V','W','X','Y'],
    ];

    $tl = count($gatHerteam[$type]);
    $vStr = "";
    for ($i=0;$i<$len;$i++){
        $tindex = mt_rand(0,($tl-1));
        $vStr .= $gatHerteam[$type][$tindex];
    }
    return $vStr;
}

/**
*错误代码对应的消息头
*@param $num 错误代码
*@return header 消息头
*/
function response_header($num)
{
    $http = array (
        100 => "HTTP/1.1 100 Continue",
        101 => "HTTP/1.1 101 Switching Protocols",
        200 => "HTTP/1.1 200 OK",
        201 => "HTTP/1.1 201 Created",
        202 => "HTTP/1.1 202 Accepted",
        203 => "HTTP/1.1 203 Non-Authoritative Information",
        204 => "HTTP/1.1 204 No Content",
        205 => "HTTP/1.1 205 Reset Content",
        206 => "HTTP/1.1 206 Partial Content",
        300 => "HTTP/1.1 300 Multiple Choices",
        301 => "HTTP/1.1 301 Moved Permanently",
        302 => "HTTP/1.1 302 Found",
        303 => "HTTP/1.1 303 See Other",
        304 => "HTTP/1.1 304 Not Modified",
        305 => "HTTP/1.1 305 Use Proxy",
        307 => "HTTP/1.1 307 Temporary Redirect",
        400 => "HTTP/1.1 400 Bad Request",
        401 => "HTTP/1.1 401 Unauthorized",
        402 => "HTTP/1.1 402 Payment Required",
        403 => "HTTP/1.1 403 Forbidden",
        404 => "HTTP/1.1 404 Not Found",
        405 => "HTTP/1.1 405 Method Not Allowed",
        406 => "HTTP/1.1 406 Not Acceptable",
        407 => "HTTP/1.1 407 Proxy Authentication Required",
        408 => "HTTP/1.1 408 Request Time-out",
        409 => "HTTP/1.1 409 Conflict",
        410 => "HTTP/1.1 410 Gone",
        411 => "HTTP/1.1 411 Length Required",
        412 => "HTTP/1.1 412 Precondition Failed",
        413 => "HTTP/1.1 413 Request Entity Too Large",
        414 => "HTTP/1.1 414 Request-URI Too Large",
        415 => "HTTP/1.1 415 Unsupported Media Type",
        416 => "HTTP/1.1 416 Requested range not satisfiable",
        417 => "HTTP/1.1 417 Expectation Failed",
        500 => "HTTP/1.1 500 Internal Server Error",
        501 => "HTTP/1.1 501 Not Implemented",
        502 => "HTTP/1.1 502 Bad Gateway",
        503 => "HTTP/1.1 503 Service Unavailable",
        504 => "HTTP/1.1 504 Gateway Time-out"
    );
    header($http[$num]);
}

/**
 * 请求错误数据返回
 * @param $error_code Integer 错误码
 * @param $msg String 错误信息
 * @param $option  Array  扩展信息
 */
function back($error_code = 10001,$msg = 'success',$option = [])
{
    if($option)
    {
    	return ['code'=>$error_code,'msg'=>$msg,'option'=>$option];
    }
    return ['code'=>$error_code,'msg'=>$msg];
}
/**
 * 请求错误数据返回
 * @param $error_code Integer 错误码
 * @param $msg String 错误信息
 * @param $option  Array  扩展信息
 */
function backlist($error_code = 10001,$msg = 'success',$option = [],$count = 0)
{
    return ['code'=>$error_code,'msg'=>$msg,'option'=>$option,'count'=>$count];
}
/**
 * 建目录
 *@param $path 文件夹路径
 * @return bool
 */
function make_dir($path)
{
    $path = str_replace(array('/', '\\', '//', '\\\\'), DIRECTORY_SEPARATOR, $path);
    $dirs = explode(DIRECTORY_SEPARATOR, $path);
    $tmp = '';
    foreach ($dirs as $dir) 
    {
        $tmp .= $dir . DIRECTORY_SEPARATOR;
        if (!file_exists($tmp) && !mkdir($tmp, 0777)) 
        {
            return $tmp;
        }
    }
    return true;
}

/**
 * 限制操作频率
 * @param $last_time int  需要比较的时间
 * @param $limit int 限制的时间，单位为S
 * @param $error_code Integer 错误码
 * @param $msg String 错误信息
 */
function limit_operation_time($last_time,$limit)
{
    if((time()-$last_time) < $limit)
    {
        return false;
    }
    return true;
}

/**
 * 异常抛出方法封装
 * @param $err_code
 * @param $http_code
 * @param string $msg
 */
function throwError($err_code,$msg = 'error',$http_code = 200)
{
	header('Content-Type:application/json; charset=utf-8');
    response_header($http_code);
    exit(json_encode(back($err_code,$msg),JSON_UNESCAPED_UNICODE));
}

